package lion.netty4.message;

import java.io.IOException;

import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;

public class RequestMessageRaw {

	private int msgcode;

	private ByteBuf buffer;

	public RequestMessageRaw(ByteBuf byteBuf) {
		buffer = byteBuf;
		this.msgcode = buffer.readUnsignedShortLE();
	}

	public int getMsgCode() {
		return msgcode;
	}

	public byte readByte() {
		return buffer.readByte();
	}

	public short readShort() {
		return buffer.readShortLE();
	}

	public int readInt() {
		return buffer.readIntLE();
	}

	public long readLong() {
		return buffer.readLongLE();
	}

	public short readUnsignedByte() {
		return buffer.readUnsignedByte();
	}

	public int readUnsignedShort() {
		return buffer.readUnsignedShortLE();
	}

	public long readUnsignedInt() {
		return buffer.readUnsignedIntLE();
	}

	public ByteBuf readByteArray() {
		int utflen = buffer.readIntLE();
		return buffer.readBytes(utflen);
	}
	
	public void writeByteArray(byte[] content) {
		buffer.writeShortLE(content.length);
		if (content.length > 0) {
			buffer.writeBytes(content);
		}
	}

	public void writeByteArray(ByteBuf content) {
		buffer.writeShortLE(content.readableBytes());
		if (content.readableBytes() > 0) {
			buffer.writeBytes(content);
		}
	}

	public String readString() throws IOException {
		int utflen = buffer.readUnsignedShortLE();
		if (utflen == 0) {
			return "";
		}
		return buffer.readBytes(utflen).toString(CharsetUtil.UTF_8);
	}

	public boolean readBool() {
		return buffer.readBoolean();
	}

	public void releaseBuffer() {
		buffer.release();
	}

	public int getLength() {
		return buffer.readableBytes();
	}

}
